/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.core.interceptor;

import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.Token;
import com.baomidou.kisso.web.interceptor.KissoAbstractInterceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JplusSsoInterceptor extends KissoAbstractInterceptor implements Interceptor {

    private static final Log log = Log.getLog(JplusSsoInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        HttpServletRequest request = inv.getController().getRequest();
        HttpServletResponse response = inv.getController().getResponse();
        Token token = SSOHelper.getToken(request);
        if (token == null) {
            try {
                log.info("logout. request url:" + request.getRequestURL());
                SSOHelper.clearRedirectLogin(request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            request.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
            inv.invoke();
        }
    }
}
